package com.ms.orm.util;
import com.ms.common.util.StringUtils;

/**
 * @author zdh
 */
public class TableNameFinder {

    public static String convertToSnakeCaseTableName(String className) {
        if (className == null || className.isEmpty()) {
            return "";
        }

        StringBuilder tableNameBuilder = new StringBuilder();
        //前一个字符是否是大写字符
        boolean wasPreviousCharUpper = false;

        for (int i = 0; i < className.length(); i++) {
            char c = className.charAt(i);
            //当前字符是否是大写
            boolean isCurrentCharUpper = Character.isUpperCase(c);
            //下一个字符是否是大写，i+1 < className.length()
            boolean nextCharUpper = true;
            if(i<className.length()-2){
                nextCharUpper = Character.isUpperCase(className.charAt(i+1));
            }
            if(i==0){
                //1、第一个字符直接转换成小写
                tableNameBuilder.append(Character.toLowerCase(c));
            }else{
                 if(wasPreviousCharUpper && isCurrentCharUpper && !nextCharUpper){
                    //2、前一个字符是大写，当前字母是大写，下一个字符是小写，则在当前字母前插入 下划线 "_"
                    tableNameBuilder.append("_");
                 }else if(!wasPreviousCharUpper && isCurrentCharUpper){
                     //3、前一个字符是小写，当前字符是大写，则在大写和小写字符之间插入下滑线
                     tableNameBuilder.append("_");
                 }

                 //3、将大写字母转换为小写并追加到结果字符串
                if(isCurrentCharUpper){
                    tableNameBuilder.append(Character.toLowerCase(c));
                }else{
                    tableNameBuilder.append(c);
                }
                // 更新状态
            }
            wasPreviousCharUpper = isCurrentCharUpper;

        }

        return tableNameBuilder.toString();
    }

    public static void main(String[] args) {
        // 测试方法
        System.out.println(convertToSnakeCaseTableName("UserProfile")); // 输出 user_profile
        System.out.println(convertToSnakeCaseTableName("UserAddressInfo")); // 输出 user_address_info
        System.out.println(convertToSnakeCaseTableName("HTTPResponseCode")); // 输出 http_response_code
        System.out.println(convertToSnakeCaseTableName("XMLHttpRequest")); // 输出 xml_http_request

        System.out.println("----------------------------------------------------------------");

        System.out.println(StringUtils.propertyNameToColumnName("UserProfile")); // 输出 user_profile
        System.out.println(StringUtils.propertyNameToColumnName("UserAddressInfo")); // 输出 user_address_info
        System.out.println(StringUtils.propertyNameToColumnName("HTTPResponseCode")); // 输出 http_response_code
        System.out.println(StringUtils.propertyNameToColumnName("XMLHttpRequest")); // 输出 xml_http_request


    }
}
